﻿using System;
using System.Text;
using System.Collections;
using System.IO;

using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;

namespace MailProcessing
{
    public class ZipController
    {
        public bool Unzipfile(string zipFileName, out string unzipFolder)
        {
            bool ret = false;
            unzipFolder = Path.Combine(Path.GetDirectoryName(zipFileName), Path.GetFileNameWithoutExtension(zipFileName));
            Directory.CreateDirectory(unzipFolder);
            try
            {
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFileName)))
                {
                    ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName = Path.GetFileName(theEntry.Name);

                        // create directory
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(string.Format(@"{0}\{1}", unzipFolder,directoryName));
                        }

                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(String.Format(@"{0}\{1}", unzipFolder, theEntry.Name)))
                            {

                                int size = 2048;
                                byte[] data = new byte[2048];
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size > 0)
                                    {
                                        streamWriter.Write(data, 0, size);
                                    }
                                    else
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    ret = true;
                }
            }
            catch (Exception ex)
            { 
                
            }
            return ret;
        }
    }
}
